<template>
  <div class="page-list-live">
    <el-row>
      <el-col :span="5" style="padding-right: 20px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">用户组织架构</div>
          <!-- <div style="margin-bottom: 20px; display: flex">
            <el-input v-model="filterText" style="margin-right: 10px" placeholder="输入关键字进行过滤" />
            <el-button size="mini" @click="getFilterText">搜索</el-button>
          </div> -->

          <el-tree ref="tree" node-key="id" class="filter-tree" :data="roleData" :props="defaultProps" show-checkbox :filter-node-method="filterNode" @check-change="handleCheckChange" />
        </el-card>
      </el-col>
      <el-col :span="19">
        <PageList>
          <template #header>用户列表</template>
          <!-- 表单搜索 -->
          <template #filter>
            <ListFilter :form="topFilter" @search="search" @reset="resetHandle" />
          </template>
          <template #tips>
            <el-button icon="el-icon-document-add" type="primary" class="box" @click="handleAdd">新增用户</el-button>
          </template>
          <template #table>
            <ListTable ref="clientTable" :loading="tableLoading" :table-data="tableData" :table-col="tableCol">
              <template slot="col1" slot-scope="scope">
                <el-button :loading="scope.row.loadingDel" size="mini" icon="el-icon-edit" style="padding: 0px" type="text" @click="handleRowEdit(scope.row)">编辑</el-button>
                <el-button
                  :disabled="scope.row.isSuperAdmin"
                  :class="scope.row.isSuperAdmin ? 'disable' : ''"
                  :loading="scope.row.loadingDel"
                  :title="scope.row.isSuperAdmin ? '超级管理员账号禁止删除' : '删除'"
                  size="mini"
                  icon="el-icon-delete"
                  type="text"
                  style="color: red; padding: 0px"
                  @click="handleRowDel(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </ListTable>
          </template>
        </PageList>
      </el-col>
    </el-row>

    <AddManager ref="AddManager" @getList="refreshPage" />
  </div>
</template>

<script>
import listMixin from '@/mixins/list'
import ListFilter from '@/components/ListFilter'
import { HostUserSearch, HostUserDel } from '@/api/HostUser'
import { RoleSearch } from '@/api/Role'
import AddManager from './components/AddManager'
export default {
  components: {
    ListFilter,
    AddManager
  },
  mixins: [listMixin],
  data() {
    return {
      // 选中的公司ID
      roleCheckdId: '',
      filterText: '', // 树形结构搜索框
      // 树形结构显示的值
      defaultProps: {
        children: 'children',
        label: 'roleName'
      },
      roleData: [], // 树形数据
      topFilter: {
        showName: {
          label: '用户名',
          placeholder: '请输入用户名称'
        }
      },
      tableData: [],
      tableCol: [
        { type: 'index', label: '序号', width: '160px' },
        { prop: 'showName', label: '用户名' },
        { prop: 'loginName', label: '登录账号' },
        {
          prop: 'role',
          label: '是否是管理员',
          formatter(row, col, cell) {
            return row.isAdmin ? '是' : '否'
          }
        },
        {
          prop: 'departString',
          label: '所属组织架构',
          width: '260px',
          align: 'left'
        },
        { label: '操作', custom: 'col1' }
      ]
    }
  },
  mounted() {
    this.getRoleHandle()
  },
  methods: {
    resetHandle(value) {
      if (this.roleCheckdId) {
        value.search = [{ key: 'roleId', value: this.roleCheckdId, operation: 0 }]
      }
      this.handleReset(value)
    },
    // 树结构查询
    getFilterText() {
      this.$refs.tree.filter(this.filterText)
    },
    // 选中树结构
    handleCheckChange(data, checked, indeterminate) {
      var roleIds = this.$refs.tree.getCheckedKeys()
      // 获取需要的id
      this.roleCheckdId = data.id
      const obj = {
        pageIndex: 1,
        pageSize: 10,
        search: [{ key: 'roleId', value: roleIds.join(','), operation: 7 }]
      }
      this.handleSearch(obj)
    },
    refreshPage() {
      if (this.roleCheckdId !== '') {
        var roleIds = this.$refs.tree.getCheckedKeys()
        const obj = {
          pageIndex: 1,
          pageSize: 10,
          search: [{ key: 'roleId', value: roleIds.join(','), operation: 7 }]
        }
        this.handleSearch(obj)
      } else {
        this.getList()
      }
    },
    // 查询树结构
    filterNode(value, data) {
      if (!value) return true
      return data.roleName.indexOf(value) !== -1
    },
    async getList(query) {
      this.tableData = []
      try {
        const obj = query || {
          pageIndex: 1,
          pageSize: 10
        }
        console.info('search', obj)
        obj.orderBy = 'createdTime'
        obj.orderByAscent = false
        const {
          data: { items, pageIndex, count }
        } = await HostUserSearch(obj)
        console.info('HostUserSearch', pageIndex)
        this.$refs['clientTable'].update({ page: pageIndex, count })
        this.tableData = items
        this.$nextTick(() => {
          this.tableLoading = false
        })
      } catch (err) {
        console.log(err)
      }
    },
    async getRoleHandle() {
      try {
        const obj = {
          pageIndex: 1,
          pageSize: 1e8
        }
        if (obj.search === undefined) {
          obj.search = []
        }
        obj.search.push({
          key: 'parentId',
          value: 0,
          operation: 0
        })
        const {
          data: { items }
        } = await RoleSearch(obj)
        this.roleData = items
      } catch (error) {
        console.log(error)
      }
    },
    handleAdd() {
      this.$refs['AddManager'].open()
      this.$refs['AddManager'].getRole()
    },
    search(obj) {
      if (obj.search) {
        var roleIds = this.$refs.tree.getCheckedKeys()
        if (roleIds.length > 0) {
          obj.search.push({
            key: 'roleId',
            value: roleIds.join(','),
            operation: 7,
            relationship: 0
          })
        }
      }
      this.getList(obj)
    },
    async handleRowEdit(row) {
      // 设置编辑模式
      await this.$store.dispatch('user/setEdit', {
        status: true,
        id: row.id
      })
      await this.$refs['AddManager'].getRole()
      this.$refs['AddManager'].open(row)
    },
    async delRowReq(row) {
      try {
        const obj = { id: row.id, value: null }
        await HostUserDel(obj)
        // row.loadingDel = false
        await this.getList()
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      } catch (err) {
        // row.loadingDel = false
        this.$message({
          type: 'error',
          message: '删除失败'
        })
        console.error('handleRowDel err: ', err)
      }
    },
    handleRowDel(row) {
      // row.loadingDel = true
      this.$_delConfirm(
        '该用户',
        () => {
          this.delRowReq(row)
        },
        () => {
          // row.loadingDel = false
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
  .disable {
    color: #ccc !important;
  }
  .el-button:focus,
  .el-button:focus:hover {
    color: #586aa6 !important;
  }
  .box:focus:hover {
    color: #fff !important;
  }
  .el-card {
    min-height: 600px;
    ::v-deep.el-card__header {
      background-color: #d3dbeb;
    }
  }
</style>
